import {useEffect, useState} from "react";

export const isFalsy = (value : unknown) => value === 0 ? false : !value

export const isVoid = (value : unknown) => value === undefined || value === null || value === ''
//在一个函数里，改变传入对象的值是不好的 {[key:string]:unknown}表示是键-值形式的object类型
export const cleanObject = (object: {[key:string]:unknown}) =>{
    const result = {...object}
    Object.keys(result).forEach(key => {
        const value = result[key]
        if(isVoid(value)){
            delete result[key]
        }
    })
    return result
}

export const useMount = (callback: () => void) => {
    useEffect(() => {
        callback()
        // todo 依赖项不能加callback，这个和useCallback以及useMemo有关系
        //eslint-disable-next-line react-hooks/exhaustive-deps
    }, [])
}

export const useDebounce =<V>(value : V, delay ?: number) => {
    const [debouncedValue, setDebouncedValue] = useState(value)
    useEffect(() => {
        const timeOut = setTimeout(() => setDebouncedValue(value), delay)
        return () => clearTimeout(timeOut)
    },[value, delay])
    return debouncedValue
}